{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:react-aria-components';
import typesDocs from 'docs:@react-types/shared/src/events.d.ts';
import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs';
import styles from '@react-spectrum/docs/src/docs.css';
import packageData from 'react-aria-components/package.json';
import Anatomy from '@react-aria/datepicker/docs/daterangepicker-anatomy.svg';
import ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleList} from '@react-spectrum/docs/src/ExampleList';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import {Keyboard} from '@react-spectrum/text';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Buttons
keywords: [button, aria, form]
type: component
---

# Button

<PageDescription>{docs.exports.Button.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['Button']}
  sourceData={[
    {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/button/'}
  ]} />

## Example

```tsx example
import {Button} from 'react-aria-components';

<Button onPress={() => alert('Hello world!')}>Press me</Button>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
@import "@react-aria/example-theme";

.react-aria-Button {
  color: var(--text-color);
  background: var(--button-background);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  appearance: none;
  vertical-align: middle;
  font-size: 1rem;
  text-align: center;
  margin: 0;
  outline: none;
  padding: 6px 10px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;

  &[data-pressed] {
    box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
    background: var(--button-background-pressed);
    border-color: var(--border-color-pressed);
  }

  &[data-focus-visible] {
    outline: 2px solid var(--focus-ring-color);
    outline-offset: -1px;
  }
}
```

</details>

## Features

On the surface, building a custom styled button seems simple. However, there are many
cross browser inconsistencies in interactions and accessibility features to consider.
`Button` handles all of these interactions for you, so you can focus on the styling.

* **Styleable** – Hover, press, and keyboard focus states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.
* **Accessible** – Uses a native `<button>` element under the hood, with support for the <Keyboard>Space</Keyboard> and <Keyboard>Enter</Keyboard> keys.
* **Cross-browser** – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

Read our [blog post](/blog/building-a-button-part-1.html) about the complexities of building buttons that work well across devices and interaction methods to learn more.

## Anatomy

Buttons consist of a clickable area usually containing a textual label or an icon
that users can click to perform an action. In addition, keyboard users may activate
buttons using the <Keyboard>Space</Keyboard> or <Keyboard>Enter</Keyboard> keys.

If a visual label is not provided (e.g. an icon only button), then an `aria-label` or
`aria-labelledby` prop must be passed to identify the button to assistive technology.

## Examples

<ExampleList tag="button" />

## Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured [Storybook](https://storybook.js.org/) that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="button" />

## Events

`Button` supports user interactions via mouse, keyboard, and touch. You can handle all of these via the `onPress` prop. This is similar to the standard `onClick` event, but normalized to support all interaction methods equally. In addition, the `onPressStart`, `onPressEnd`, and `onPressChange` events are fired as the user interacts with the button.

Each of these handlers receives a <TypeLink links={typesDocs.links} type={typesDocs.exports.PressEvent} />, which exposes information about the target and the type of event that triggered the interaction. See [usePress](usePress.html) for more details.

```tsx example
function Example() {
  let [pointerType, setPointerType] = React.useState('');

  return (
    <>
      <Button
        onPressStart={e => setPointerType(e.pointerType)}
        onPressEnd={() => setPointerType('')}>
        Press me
      </Button>
      <p>{pointerType ? `You are pressing the button with a ${pointerType}!` : 'Ready to be pressed.'}</p>
    </>
  )
}
```

## Disabled

A `Button` can be disabled using the `isDisabled` prop.

```tsx example
<Button isDisabled>Pin</Button>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Button {
  &[data-disabled]{
    border-color: var(--border-color-disabled);
    color: var(--text-color-disabled);
  }
}
```

</details>

## Pending

A `Button` can be put into a pending state using the `isPending` prop.
This is useful when an action takes a long time to complete, and you want to provide feedback to the user that the action is in progress.
The pending state announces the state change to assistive technologies and disables interactions with the exception of focus.

A [ProgressBar](ProgressBar.html) component is required to show the pending state correctly.
Make sure to internationalize the `aria-label` you pass to the [ProgressBar](ProgressBar.html) component.

```tsx example
import {useState} from 'react';

function PendingButton(props) {
  let [isPending, setPending] = useState(false);

  let handlePress = (e) => {
    setPending(true);
    setTimeout(() => {
      setPending(false);
    }, 5000);
  };

  return (
    <Button
      {...props}
      isPending={isPending}
      onPress={handlePress}>
        {({isPending}) => (
          <>
            {!isPending && <span>Save</span>}
            {isPending && (
              // See below
              <MyProgressCircle aria-label="Saving..." isIndeterminate />
            )}
          </>
        )}
    </Button>
  );
}
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> MyProgressCircle</summary>

```tsx example render=false export=true
import {ProgressBar} from 'react-aria-components';
import type {ProgressBarProps} from 'react-aria-components';

function MyProgressCircle(props: ProgressBarProps) {
  return (
    <ProgressBar {...props}>
      <svg width="16" height="16" viewBox="0 0 24 24" style={{display: 'block'}}>
        <path fill="currentColor" d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" opacity=".25" />
        <path fill="currentColor" d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z">
          <animateTransform attributeName="transform" type="rotate" dur="0.75s" values="0 12 12;360 12 12" repeatCount="indefinite"/>
        </path>
      </svg>
    </ProgressBar>
  );
}
```

</details>

### Accessibility

**Note:**
The `ProgressBar` must be in the accessibility tree as soon as the button becomes pending, even if it is not visible.
For example, if you'd like to delay showing a spinner until a minimum amount of time passes, you could use `opacity: 0` to hide it so it is still available to screen readers.
Do not use `visibility: hidden` or `display: none` since these remove the element from the accessibility tree.

Additionally, you may choose to keep the button's contents in the DOM while the button is pending, e.g. to preserve the button's layout.
If you hide the contents with `visibility: hidden`, the accessibility label for the button will only include the ProgressBar, so it should have a descriptive `aria-label` (e.g. "Saving").
You can also choose to keep the button's contents in the accessibility tree by using `opacity: 0`, in which case the `ProgressBar`'s label will be combined with the contents (e.g. "Save, pending").

Try the above example and the one below with a screen reader to see the difference in behavior.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show example</summary>

```tsx example
function PendingDelayed(props) {
  let [isPending, setPending] = useState(false);

  let handlePress = (e) => {
    setPending(true);
    setTimeout(() => {
      setPending(false);
    }, 5000);
  };

  return (
    <Button
      {...props}
      isPending={isPending}
      onPress={handlePress}
      style={{position: 'relative'}}>
        {({isPending}) => (
          <>
            <span className={isPending ? 'pending' : undefined}>Save</span>
            {isPending && (
              <MyProgressCircle aria-label="in progress" isIndeterminate className="spinner" />
            )}
          </>
        )}
    </Button>
  );
}
```

```css
@keyframes toggle {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation: toggle 1s steps(1);
  opacity: 1;
}

.pending {
  animation: toggle 1s reverse steps(1, jump-start);
  opacity: 0;
}
```

</details>

## Link buttons

The `Button` component always represents a button semantically. To create a link that visually looks like a button, use the [Link](Link.html) component instead. You can reuse the same styles you apply to the `Button` component on the `Link`.

```tsx example
import {Link} from 'react-aria-components';

<Link className="react-aria-Button" href="https://adobe.com/" target="_blank">
  Adobe
</Link>
```

## Props

<PropTable component={docs.exports.Button} links={docs.links} />

## Styling

React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin `className` attribute which can be targeted using CSS selectors. These follow the `react-aria-ComponentName` naming convention.

```css
.react-aria-Button {
  /* ... */
}
```

A custom `className` can also be specified on any component. This overrides the default `className` provided by React Aria with your own.

```jsx
<Button className="my-button">
  {/* ... */}
</Button>
```

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

```css
.react-aria-Button[data-pressed] {
  /* ... */
}
```

The `className` and `style` props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like [Tailwind](https://tailwindcss.com/).

```jsx
<Button className={({isPressed}) => isPressed ? 'bg-gray-700' : 'bg-gray-600'} />
```

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the button is in a pressed state.

```jsx
<Button>
  {({isPressed}) => (
    <>
      {isPressed && <PressHighlight />}
      Press me
    </>
  )}
</Button>
```

The states, selectors, and render props for `Button` are documented below.

<StateTable properties={docs.exports.ButtonRenderProps.properties} />

## Advanced customization

### Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in [mergeProps](mergeProps.html)).

<ContextTable components={['Button']} docs={docs} />

This example shows a `ButtonGroup` component that renders a group of buttons. The entire group can be marked as disabled via the `isDisabled` prop, which is passed to all child buttons via the `ButtonContext` provider.

```tsx example
import {ButtonContext} from 'react-aria-components';

interface ButtonGroupProps {
  children?: React.ReactNode,
  isDisabled?: boolean
}

function ButtonGroup({children, isDisabled}: ButtonGroupProps) {
  return (
    <div style={{display: 'flex', gap: 8}}>
      {/*- begin highlight -*/}
      <ButtonContext.Provider value={{isDisabled}}>
      {/*- end highlight -*/}
        {children}
      </ButtonContext.Provider>
    </div>
  );
}

<ButtonGroup isDisabled>
  <Button>Save</Button>
  <Button>Publish</Button>
</ButtonGroup>
```

### Hooks

If you need to customize things further, such as intercepting events or customizing DOM elements, you can drop down to the lower level Hook-based API. Consume from `ButtonContext` in your component with <TypeLink links={docs.links} type={docs.exports.useContextProps} /> to make it compatible with other React Aria Components. See [useButton](useButton.html) for more details.

This example uses [Framer Motion](https://www.framer.com/motion/) to create an `AnimatedButton` component that animates based on the `isPressed` state provided by `useButton`. It can be used standalone or as a part of any React Aria component.

```tsx
import type {ButtonProps} from 'react-aria-components';
import {ButtonContext, useContextProps} from 'react-aria-components';
import {useButton} from 'react-aria';
import {motion} from 'motion/react';

const AnimatedButton = React.forwardRef((props: ButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, ButtonContext);
  ///- end highlight -///

  let {buttonProps, isPressed} = useButton(props, ref);
  return (
    <motion.button
      {...buttonProps}
      ref={ref}
      animate={{
        scale: isPressed ? 0.9 : 1
      }}>
      {props.children}
    </motion.button>
  );
});
```
